﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Mail;
using System.IO;
using System.Data.SqlClient;
using DevExpress.XtraEditors;
using DevExpress.XtraReports;
using COMOSOFT.Class;
using DevExpress.XtraReports.UI;
using DevExpress.LookAndFeel;

namespace COMOSOFT.OrderBusiness.Forms
{
    public partial class FrmSendEmail : DevExpress.XtraBars.Ribbon.RibbonForm
    {

        ClassShare cls = new ClassShare("FrmSendEmail");
        List<string> Atachfile = new System.Collections.Generic.List<string>();
        public Attachment att = null;
        public FrmSendEmail()
        {
            InitializeComponent();
            DataTable dtb = cls.GetData("sp_GetUserEmail", new string[1] { "@EID" }, new object[1] { ClassShare.Usid });
            if (dtb.Rows.Count > 0)
            {
                txt_from.Text=dtb.Rows[0][0].ToString();              
            }            
            txt_subjects.Text = "Send Purchase To Factory";
        }
        public void AddFile(string file)
        {
            Atachfile.Add(file);
            DisplayAtachfiles();
        }

        #region SaveMessage event
        EventHandler onSaveMessage;
        public event EventHandler SaveMessage { add { onSaveMessage += value; } remove { onSaveMessage -= value; } }
        protected internal virtual void RaiseSaveMessage()
        {
            if (onSaveMessage != null)
                onSaveMessage(this, EventArgs.Empty);
        }
        #endregion

        #region [send mail]
        private void bnt_sendmail_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            List<string> toArrs = new System.Collections.Generic.List<string>();
            string[] item = txt_to.Text.Split(';');
            foreach (string i in item)
            {
                if (i.Trim() != string.Empty)
                {
                    toArrs.Add(i.Trim());
                }
            }
            if(toArrs.Count>0)
               SendMail(txt_from.Text, toArrs.ToArray(), txt_subjects.Text,Atachfile.ToArray(), rich_body.HtmlText);
        }
        #endregion

        #region[action send mail]
        public void SendMail(string from_address, string[] to_address, string subjects,string[] attachfiles,string body)
        {
            try
            {
                MailMessage message = new MailMessage();
                SmtpClient Client = new SmtpClient();
                Client.Host = "smtp.gmail.com";
                Client.Port = 587;
                Client.Credentials = new System.Net.NetworkCredential("dinhdongcntt@gmail.com", "Dong_OuIt@2711");
                Client.EnableSsl = true;
                Client.DeliveryMethod = SmtpDeliveryMethod.Network;
                message.From = new MailAddress(txt_from.Text);
                message.Sender = new MailAddress(txt_from.Text);
               // message.ReplyTo = new MailAddress(txt_from.Text);
                foreach (string item in to_address)
                {
                    message.To.Add(new MailAddress(item));
                }                
                if(att!=null)
                    message.Attachments.Add(att);
                foreach (string fn in attachfiles)
                {             
                    if(fn!=att.Name)
                      message.Attachments.Add(new Attachment(fn));
                }
                message.Subject = subjects;
                message.Body = body;
                message.IsBodyHtml = true;
                Client.Send(message);
                MessageBox.Show("Email was sent successfully!");                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                this.Close();
            }
        }
        #endregion

        #region [Load file atachment]
        private void DisplayAtachfiles()
        {
            try
            {               
                while (bnt_atachfiles.Properties.Buttons.Count > 1)
                {
                    bnt_atachfiles.Properties.Buttons.RemoveAt(0);
                }
                foreach (string fn in Atachfile)
                {
                    FileInfo finfo = new FileInfo(fn);
                    Image img = null;
                    if (finfo.Extension.ToLower() == ".pdf")
                    {
                        img = imageCollection1.Images[0];
                    }
                    else if (finfo.Extension.ToLower() == ".xls")
                    {
                        img = imageCollection1.Images[1];
                    }
                    else if (finfo.Extension.ToLower() == ".xlsx")
                    {
                        img = imageCollection1.Images[1];
                    }
                    else if (finfo.Extension.ToLower() == ".doc")
                    {
                        img = imageCollection1.Images[3];
                    }
                    else if (finfo.Extension.ToLower() == ".docx")
                    {
                        img = imageCollection1.Images[3];
                    }
                    else
                        img = imageCollection1.Images[2];

                    DevExpress.Utils.SerializableAppearanceObject serializableAppreanceObje = new DevExpress.Utils.SerializableAppearanceObject();
                    serializableAppreanceObje.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Underline);
                    serializableAppreanceObje.ForeColor = System.Drawing.Color.Blue;
                    serializableAppreanceObje.Options.UseFont = true;
                    serializableAppreanceObje.Options.UseForeColor = true;
                    DevExpress.XtraEditors.Controls.EditorButton b = new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph, finfo.Name, -1, true, true, false, DevExpress.XtraEditors.ImageLocation.MiddleLeft, img, new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.None), serializableAppreanceObje, "", null, null, true);
                    b.Tag = fn;
                    bnt_atachfiles.Properties.Buttons.Insert(0, b);
                }
                GC.Collect();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region[chose file atachment]
        private void bnt_atachfiles_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                if (e.Button.Tag.ToString() == "UploadAttach")
                {
                    OpenFileDialog file = new OpenFileDialog();
                    if (file.ShowDialog() == DialogResult.OK)
                    {
                        Atachfile.Add(file.FileName);
                        DisplayAtachfiles();
                    }
                }
                else if (e.Button.Tag.ToString() != "Space")
                {
                    System.Diagnostics.Process.Start(e.Button.Tag.ToString());
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion
    }
}
